<template>
    <view class="container">
        <!-- 顶部导航栏 -->
        <view class="header">
            <view class="logo">
                <text class="logo-icon">🎵</text>
                <text class="logo-text">音乐世界</text>
            </view>
            <view class="header-actions">
                <view class="header-btn" @click="navigateToFavorite">
                    <text class="header-icon">❤️</text>
                </view>
            </view>
        </view>

        <view class="content">
            <!-- 横幅轮播图 -->
            <view class="banner">
                <swiper class="banner-swiper" 
                        :indicator-dots="true" 
                        :autoplay="true" 
                        :interval="3000" 
                        :duration="500"
                        :circular="true"
                        indicator-color="rgba(255, 255, 255, 0.5)"
                        indicator-active-color="#ffffff">
                    <swiper-item v-for="(image, index) in bannerImages" :key="index">
                        <view class="banner-overlay"></view>
                        <image :src="image" class="banner-image" mode="aspectFill"></image>
                    </swiper-item>
                </swiper>
            </view>

            <!-- 推荐歌单 -->
            <view class="section">
                <view class="section-header">
                    <text class="section-title">🎼 推荐歌单</text>
                    <text class="section-more">更多 ›</text>
                </view>
                <scroll-view class="playlist-scroll" scroll-x="true">
                    <view class="playlist-grid">
                        <!-- 创建歌单按钮 -->
                        <view class="playlist-card create-playlist-card" @click="showCreatePlaylistDialog">
                            <view class="create-icon">+</view>
                            <text class="playlist-title">创建歌单</text>
                        </view>
                        <!-- 歌单列表 -->
                        <view class="playlist-card" v-for="playlist in playlists" :key="playlist.id" @click="goToPlaylistDetail(playlist)">
                            <image :src="playlist.image" class="playlist-image"></image>
                            <text class="playlist-title">{{ playlist.title }}</text>
                            <text class="playlist-info">{{ playlist.info }}</text>
                        </view>
                    </view>
                </scroll-view>
            </view>

            <!-- 歌曲列表 -->
            <view class="section">
                <!-- 添加歌曲按钮 -->
                <view class="add-song-btn" @click="showAddSongDialog">
                    <text class="add-icon">+</text>
                </view>
                <view class="section-header">
                    <text class="section-title">🎧 热门歌曲</text>
                    <text class="song-count">{{ filteredSongList.length }} 首</text>
                </view>
                <!-- 搜索框 -->
                <SearchBox
                    placeholder="搜索歌名或原唱"
                    :value="searchQuery"
                    @input="onSearchInput"
                    @search="onSearchConfirm"
                />
                <view class="song-list" v-if="!loading">
                    <view class="song-item" 
                          v-for="(song, index) in filteredSongList" 
                          :key="song.id"
                          @click="playSong(song)">
                        <view class="song-index">{{ index + 1 }}</view>
                        <image :src="song.cover_url || '/static/logo.png'" 
                               class="song-image"></image>
                        <view class="song-info">
                            <text class="song-title">{{ song.title }}</text>
                            <text class="song-artist">🎤 {{ song.artist }}</text>
                        </view>
                        <view class="song-actions">
                            <view class="play-indicator" v-if="currentSong && currentSong.id === song.id">
                                <text class="playing-icon">🎵</text>
                            </view>
                            <view class="song-more" @click.stop="showSongMenu(song)">
                                <text class="icon">⋯</text>
                            </view>
                        </view>
                    </view>
                </view>
                <view class="loading" v-if="loading">
                    <text>加载中...</text>
                </view>
            </view>
        </view>

        <!-- 创建歌单弹窗 -->
        <view v-if="showCreateDialog" class="dialog-mask" @click="closeCreateDialog">
            <view class="dialog-content" @click.stop>
                <view class="dialog-header">
                    <text class="dialog-title">创建歌单</text>
                    <text class="dialog-close" @click="closeCreateDialog">×</text>
                </view>
                <view class="dialog-body">
                    <view class="form-item">
                        <text class="form-label">歌单名称</text>
                        <input class="form-input" v-model="newPlaylist.title" placeholder="请输入歌单名称" />
                    </view>
                    <view class="form-item">
                        <text class="form-label">歌单描述</text>
                        <input class="form-input" v-model="newPlaylist.description" placeholder="请输入歌单描述" />
                    </view>
                </view>
                <view class="dialog-footer">
                    <view class="dialog-btn dialog-btn-cancel" @click="closeCreateDialog">
                        <text>取消</text>
                    </view>
                    <view class="dialog-btn dialog-btn-confirm" @click="confirmCreatePlaylist">
                        <text>确定</text>
                    </view>
                </view>
            </view>
        </view>

        <!-- 添加歌曲弹窗 -->
        <view v-if="showAddDialog" class="dialog-mask" @click="closeAddDialog">
            <view class="dialog-content" @click.stop>
                <view class="dialog-header">
                    <text class="dialog-title">添加歌曲</text>
                    <text class="dialog-close" @click="closeAddDialog">×</text>
                </view>
                <view class="dialog-body">
                    <view class="form-item">
                        <text class="form-label">歌名</text>
                        <input class="form-input" v-model="newSong.title" placeholder="请输入歌名" />
                    </view>
                    <view class="form-item">
                        <text class="form-label">原唱</text>
                        <input class="form-input" v-model="newSong.artist" placeholder="请输入原唱" />
                    </view>
                    <view class="form-item">
                        <text class="form-label">音频文件</text>
                        <view class="file-select" @click="chooseAudioFile">
                            <text class="file-text">{{ newSong.audioFileName || '点击选择音频文件' }}</text>
                            <text class="file-icon">📁</text>
                        </view>
                    </view>
                </view>
                <view class="dialog-footer">
                    <view class="dialog-btn dialog-btn-cancel" @click="closeAddDialog">
                        <text>取消</text>
                    </view>
                    <view class="dialog-btn dialog-btn-confirm" @click="confirmAddSong">
                        <text>确定</text>
                    </view>
                </view>
            </view>
        </view>

        <!-- 音乐播放器 -->
        <music-player 
            :song="currentSong" 
            @previous="previousSong"
            @next="nextSong"
            @add-to-playlist="addToPlaylist"
            @share="shareSong"
            @download="downloadSong"
            @show-lyrics="showLyrics"
        />
    </view>
</template>

<script>
import SearchBox from '@/components/searchbox/searchbox.vue'
import MusicPlayer from '@/components/music-player/music-player.vue'
import config from '@/config.js'

export default {
    components: {
        SearchBox,
        MusicPlayer
    },
    computed: {
        // 过滤后的歌曲列表（按标题或原唱匹配）
        filteredSongList() {
            const q = (this.searchQuery || '').trim().toLowerCase();
            if (!q) return this.songList;
            return this.songList.filter(s => {
                const title = (s.title || '').toLowerCase();
                const artist = (s.artist || '').toLowerCase();
                return title.includes(q) || artist.includes(q);
            });
        }
    },
    data() {
        return {
            // 静态音频文件配置
            staticAudioFiles: [
                { name: '逃跑计划 - 夜空中最亮的星.mp3', path: '/static/逃跑计划 - 夜空中最亮的星.mp3' },
                { name: '周杰伦 - 反方向的钟.mp3', path: '/static/周杰伦 - 反方向的钟.mp3' }
            ],
            title: '音乐播放器',
            bannerImages: [
                '/static/屏幕截图 2025-10-09 211405.png',
                '/static/屏幕截图 2025-10-09 211434.png',
                '/static/屏幕截图 2025-10-09 211505.png'
            ],
			playlists: [
				{
					id: 1,
					title: '流行热歌',
					info: '25首 | 播放1.2万次',
					image: 'https://ai-public.mastergo.com/ai/img_res/647cde825adf712e96b3bc66cb67656c.jpg'
				},
				{
					id: 2,
					title: '轻音乐',
					info: '18首 | 播放8.5千次',
					image: 'https://ai-public.mastergo.com/ai/img_res/0d326ebc29d14771873128d2e0f564fd.jpg'
				}
			],
            currentSong: null,
            // 搜索关键字
            searchQuery: '',
            songList: [
                // 原有4首歌曲（添加了示例音频URL）
                {
                    id: 1,
                    title: '夜空中最亮的星',
                    artist: '逃跑计划',
                    cover_url: 'https://ai-public.mastergo.com/ai/img_res/647cde825adf712e96b3bc66cb67656c.jpg',
                    audio_url: '/static/逃跑计划 - 夜空中最亮的星.mp3',
                    duration: '04:00',
                    isLocal: true
                },
                {
                    id: 2,
                    title: '海阔天空',
                    artist: 'Beyond',
                    cover_url: 'https://ai-public.mastergo.com/ai/img_res/c259606553810742eff43369376a2a87.jpg',
                    audio_url: 'https://music.163.com/song/media/outer/url?id=346576.mp3',
                    duration: '05:20'
                },
                {
                    id: 3,
                    title: '起风了',
                    artist: '买辣椒也用券',
                    cover_url: 'https://ai-public.mastergo.com/ai/img_res/5664d87772b76472ab0cd4f1d1a44d1d.jpg',
                    audio_url: 'https://music.163.com/song/media/outer/url?id=1330348068.mp3',
                    duration: '04:40'
                },
                {
                    id: 4,
                    title: '稻香',
                    artist: '周杰伦',
                    cover_url: 'https://ai-public.mastergo.com/ai/img_res/dceca67b9c576b6031ddcfce7b27afb8.jpg',
                    audio_url: 'https://music.163.com/song/media/outer/url?id=185811.mp3',
                    duration: '03:40',
                    isPlaceholder: true
                },
                // 新增7首周杰伦歌曲
                {
                    id: 5,
                    title: '晴天',
                    artist: '周杰伦',
                    cover_url: 'https://ai-public.mastergo.com/ai/img_res/0d326ebc29d14771873128d2e0f564fd.jpg',
                    audio_url: 'https://music.163.com/song/media/outer/url?id=185668.mp3',
                    duration: '04:20',
                    isPlaceholder: true
                },
                {
                    id: 6,
                    title: '夜曲',
                    artist: '周杰伦',
                    cover_url: 'https://ai-public.mastergo.com/ai/img_res/647cde825adf712e96b3bc66cb67656c.jpg',
                    audio_url: 'https://music.163.com/song/media/outer/url?id=185809.mp3',
                    duration: '03:45',
                    isPlaceholder: true
                },
                {
                    id: 7,
                    title: '青花瓷',
                    artist: '周杰伦',
                    cover_url: 'https://ai-public.mastergo.com/ai/img_res/c259606553810742eff43369376a2a87.jpg',
                    audio_url: 'https://music.163.com/song/media/outer/url?id=185895.mp3',
                    duration: '03:12'
                },
                {
                    id: 8,
                    title: '告白气球',
                    artist: '周杰伦',
                    cover_url: 'https://ai-public.mastergo.com/ai/img_res/5664d87772b76472ab0cd4f1d1a44d1d.jpg',
                    audio_url: 'https://music.163.com/song/media/outer/url?id=436514312.mp3',
                    duration: '03:34'
                },
                {
                    id: 9,
                    title: '七里香',
                    artist: '周杰伦',
                    cover_url: 'https://ai-public.mastergo.com/ai/img_res/dceca67b9c576b6031ddcfce7b27afb8.jpg',
                    audio_url: 'https://music.163.com/song/media/outer/url?id=185819.mp3',
                    duration: '04:05'
                },
                {
                    id: 10,
                    title: '简单爱',
                    artist: '周杰伦',
                    cover_url: 'https://ai-public.mastergo.com/ai/img_res/0d326ebc29d14771873128d2e0f564fd.jpg',
                    audio_url: 'https://music.163.com/song/media/outer/url?id=185868.mp3',
                    duration: '04:28'
                }
            ],
            loading: false,
            userId: 'user_001', // 临时用户ID，实际应用中应该从登录状态获取
            showAddDialog: false,
            newSong: {
                title: '',
                artist: '',
                audioFile: null,
                audioFileName: ''
            },
            showCreateDialog: false,
            newPlaylist: {
                title: '',
                description: ''
            }
        }
    },
    onLoad() {
        // 加载用户自定义歌曲
        this.loadCustomSongs();
        
        // 加载用户自定义歌单
        this.loadCustomPlaylists();
        
        // 设置第一首歌为当前播放
        if (this.songList.length > 0) {
            this.currentSong = this.songList[0];
        }
        // 启动时尝试同步离线保存的歌曲信息
        this.syncPendingSongSaves();
    },
    methods: {
        onSearchInput(val) {
            this.searchQuery = val || '';
        },
        onSearchConfirm(val) {
            this.searchQuery = (typeof val === 'string') ? val : (val && val.detail && val.detail.value) || '';
        },
        // 加载用户自定义歌曲
        loadCustomSongs() {
            const customSongs = uni.getStorageSync('customSongs') || [];
            if (customSongs.length > 0) {
                // 将自定义歌曲添加到列表开头
                this.songList = [...customSongs, ...this.songList];
            }
        },
        
        // 加载用户自定义歌单
        loadCustomPlaylists() {
            const customPlaylists = uni.getStorageSync('customPlaylists') || [];
            if (customPlaylists.length > 0) {
                // 将自定义歌单添加到列表
                this.playlists = [...this.playlists, ...customPlaylists];
            }
        },
        
        // 加载歌曲列表 - 已经在data中直接定义了歌曲数据，不需要从服务器加载
        loadSongs() {
            // 这个方法保留但不做任何操作，以防其他地方调用
            console.log('使用本地歌曲数据');
        },
        
        // 动态解析可用的后端地址并缓存
        async resolveApiUrl() {
            try {
                const cached = uni.getStorageSync('resolvedApiUrl');
                if (cached) return cached;
            } catch (e) {}
            const candidates = [];
            // 优先使用配置
            try { if (config.apiUrl) candidates.push(config.apiUrl); } catch (e) {}
            try { if (config.serverUrl && !candidates.includes(config.serverUrl)) candidates.push(config.serverUrl); } catch (e) {}
            // 本机开发者工具常用
            if (!candidates.includes('http://localhost:3000')) candidates.push('http://localhost:3000');

            for (const base of candidates) {
                try {
                    const res = await uni.request({
                        url: `${base}/health`,
                        method: 'GET',
                        timeout: 2000
                    });
                    if (res.statusCode === 200) {
                        uni.setStorageSync('resolvedApiUrl', base);
                        return base;
                    }
                } catch (e) {
                    // 忽略，尝试下一个
                }
            }
            // 全部失败时退回首选项，后续由离线机制兜底
            return candidates[0] || 'http://localhost:3000';
        },

        // 统一请求封装：2xx 与 409 都视为成功，400 提供详细错误信息
        requestJson(base, path, data) {
            return new Promise((resolve, reject) => {
                uni.request({
                    url: `${base}${path}`,
                    method: 'POST',
                    data,
                    timeout: 8000,
                    success: (res) => {
                        const sc = res.statusCode;
                        if ((sc >= 200 && sc < 300) || sc === 409) {
                            resolve(res);
                        } else {
                            // 提供更详细的错误信息
                            let errorMsg = `HTTP ${sc}`;
                            try {
                                const responseData = typeof res.data === 'string' ? JSON.parse(res.data) : res.data;
                                if (responseData && responseData.message) {
                                    errorMsg = `${errorMsg}: ${responseData.message}`;
                                }
                            } catch (e) {
                                // 如果解析失败，使用原始错误信息
                            }
                            reject(new Error(errorMsg));
                        }
                    },
                    fail: (err) => {
                        reject(err);
                    }
                });
            });
        },

        // 先查后写：避免产生 409（已存在则直接跳过）
        // 兼容不同后端返回结构与字段名（如 songs: [{title,artist}] 或 data:[{name}]）
        async existsOnServer(base, path, fields, value) {
            try {
                const res = await uni.request({
                    url: `${base}${path}`,
                    method: 'GET',
                    timeout: 8000
                });
                if (res.statusCode >= 200 && res.statusCode < 300) {
                    const d = res.data || {};
                    // 可能结构：{success:true,data:[...]}, {code:0,data:[...]}, {songs:[...]}, 直接是数组
                    let arr = Array.isArray(d) ? d
                        : (Array.isArray(d.data) ? d.data
                        : (Array.isArray(d.songs) ? d.songs
                        : (Array.isArray(d.songers) ? d.songers : [])));
                    if (!Array.isArray(arr) && d.data && typeof d.data === 'object') {
                        // 兼容 { data: { songs: [...] } }
                        if (Array.isArray(d.data.songs)) arr = d.data.songs;
                        if (Array.isArray(d.data.songers)) arr = d.data.songers;
                    }
                    const keys = Array.isArray(fields) ? fields : [fields];
                    return Array.isArray(arr) && arr.some(item => {
                        if (!item || typeof item !== 'object') return false;
                        return keys.some(k => (item[k] || '') === value);
                    });
                }
            } catch (e) {}
            return false;
        },
        
        // 同步离线保存的歌曲信息
        async syncPendingSongSaves() {
            try {
                const pending = uni.getStorageSync('pendingSongSaves') || [];
                if (!pending.length) return;
                const apiUrl = await this.resolveApiUrl();
                const stillPending = [];
                for (const item of pending) {
                    try {
                        const songExist = await this.existsOnServer(apiUrl, '/api/songs', ['name','title'], item.name);
                        if (!songExist) {
                            await this.requestJson(apiUrl, '/api/songs', { title: item.name, artist: item.artist });
                        }
                        const singerExist = await this.existsOnServer(apiUrl, '/api/songers', ['name','artist','singer','singer_name'], item.artist);
                        if (!singerExist) {
                            await this.requestJson(apiUrl, '/api/songers', { name: item.artist });
                        }
                    } catch (e) {
                        stillPending.push(item);
                    }
                }
                uni.setStorageSync('pendingSongSaves', stillPending);
                if (stillPending.length === 0) {
                    console.log('离线歌曲信息已全部同步');
                } else {
                    console.log(`仍有 ${stillPending.length} 条待同步`);
                }
            } catch (e) {
                console.warn('同步离线歌曲信息失败:', e && e.message);
            }
        },
        
        navigateToFavorite() {
            uni.switchTab({
                url: '/pages/favorite/favorite'
            });
        },
        onSearch(keyword) {
            if (keyword.trim()) {
                this.searchSongs(keyword);
            }
        },
        
        // 跳转到歌单详情
        goToPlaylistDetail(playlist) {
            uni.navigateTo({
                url: `/pages/playlistDetail/playlistDetail?id=${playlist.id}`
            });
        },
        
        // 显示创建歌单对话框
        showCreatePlaylistDialog() {
            this.showCreateDialog = true;
        },
        
        // 关闭创建歌单对话框
        closeCreateDialog() {
            this.showCreateDialog = false;
            this.newPlaylist = {
                title: '',
                description: ''
            };
        },
        
        // 确认创建歌单
        confirmCreatePlaylist() {
            if (!this.newPlaylist.title) {
                uni.showToast({
                    title: '请输入歌单名称',
                    icon: 'none'
                });
                return;
            }
            
            const playlist = {
                id: Date.now(),
                title: this.newPlaylist.title,
                info: this.newPlaylist.description || '自定义歌单',
                image: 'https://ai-public.mastergo.com/ai/img_res/647cde825adf712e96b3bc66cb67656c.jpg',
                songs: [],
                isCustom: true
            };
            
            // 添加到歌单列表
            this.playlists.push(playlist);
            
            // 保存到本地存储
            let customPlaylists = uni.getStorageSync('customPlaylists') || [];
            customPlaylists.push(playlist);
            uni.setStorageSync('customPlaylists', customPlaylists);
            
            uni.showToast({
                title: '创建成功',
                icon: 'success'
            });
            
            this.closeCreateDialog();
        },
        
        // 搜索歌曲
        async searchSongs(keyword) {
            this.loading = true;
            try {
                const response = await uni.request({
                    url: 'http://localhost:3000/api/music/search',
                    method: 'GET',
                    data: { q: keyword }
                });
                
                if (response.data.code === 0) {
                    this.songList = response.data.data;
                    uni.showToast({
                        title: `找到 ${this.songList.length} 首歌曲`,
                        icon: 'none'
                    });
                } else {
                    uni.showToast({
                        title: response.data.message,
                        icon: 'none'
                    });
                }
            } catch (error) {
                console.error('搜索失败:', error);
                uni.showToast({
                    title: '搜索失败',
                    icon: 'none'
                });
            } finally {
                this.loading = false;
            }
        },
        
        // 播放歌曲
        async playSong(song) {
            // 检查是否是摆设歌曲
            if (song.isPlaceholder) {
                // 摆设歌曲不播放，但可以点击到其他功能
                return;
            }
            
            this.currentSong = song;
            try {
                await this.recordPlayHistory(song.id);
                uni.showToast({ title: '已记录到历史', icon: 'none' });
            } catch (e) {
                // 已在 recordPlayHistory 打印错误
            }
        },
        
        // 上一首
        previousSong() {
            const currentIndex = this.songList.findIndex(song => song.id === this.currentSong.id);
            let prevIndex = currentIndex > 0 ? currentIndex - 1 : this.songList.length - 1;
            
            // 跳过摆设歌曲
            while (this.songList[prevIndex].isPlaceholder && prevIndex !== currentIndex) {
                prevIndex = prevIndex > 0 ? prevIndex - 1 : this.songList.length - 1;
            }
            
            this.playSong(this.songList[prevIndex]);
        },
        
        // 下一首
        nextSong() {
            const currentIndex = this.songList.findIndex(song => song.id === this.currentSong.id);
            let nextIndex = currentIndex < this.songList.length - 1 ? currentIndex + 1 : 0;
            
            // 跳过摆设歌曲
            while (this.songList[nextIndex].isPlaceholder && nextIndex !== currentIndex) {
                nextIndex = nextIndex < this.songList.length - 1 ? nextIndex + 1 : 0;
            }
            
            this.playSong(this.songList[nextIndex]);
        },
        
        // 记录播放历史
        async recordPlayHistory(songId) {
            try {
                // 获取当前播放历史
                let history = uni.getStorageSync('playHistory') || [];
                
                // 查找当前歌曲
                const song = this.songList.find(s => s.id === songId);
                if (!song) return;
                
                // 移除重复的记录
                history = history.filter(item => item.id !== songId);
                
                // 添加到开头
                history.unshift({
                    ...song,
                    playTime: new Date().getTime()
                });
                
                // 保留最近50条记录
                if (history.length > 50) {
                    history = history.slice(0, 50);
                }
                
                // 保存到本地存储
                uni.setStorageSync('playHistory', history);
                
                console.log('播放历史已记录:', song.title);
            } catch (error) {
                console.error('记录播放历史失败:', error);
            }
        },
        
        // 添加到播放列表
        addToPlaylist(song) {
            uni.showToast({
                title: '添加到播放列表功能待实现',
                icon: 'none'
            });
        },
        
        // 分享歌曲
        shareSong(song) {
            uni.showToast({
                title: '分享功能待实现',
                icon: 'none'
            });
        },
        
        // 下载歌曲
        downloadSong(song) {
            uni.showToast({
                title: '下载功能待实现',
                icon: 'none'
            });
        },
        
        // 显示歌词
        showLyrics(song) {
            uni.showToast({
                title: '歌词功能待实现',
                icon: 'none'
            });
        },
        
        // 显示歌曲菜单
        showSongMenu(song) {
            // 判断是否是用户自己添加的歌曲
            const customSongs = uni.getStorageSync('customSongs') || [];
            const isCustomSong = customSongs.some(s => s.id === song.id);
            
            // 根据是否是自定义歌曲显示不同的菜单
            const itemList = isCustomSong 
                ? ['添加到喜欢', '添加到收藏', '查看详情', '删除'] 
                : ['添加到喜欢', '添加到收藏', '查看详情'];
            
            uni.showActionSheet({
                itemList: itemList,
                success: (res) => {
                    if (isCustomSong) {
                        // 自定义歌曲的菜单
                        switch (res.tapIndex) {
                            case 0:
                                this.addToLikes(song);
                                break;
                            case 1:
                                this.addToCollection(song);
                                break;
                            case 2:
                                this.showSongDetail(song);
                                break;
                            case 3:
                                this.deleteCustomSong(song);
                                break;
                        }
                    } else {
                        // 默认歌曲的菜单
                        switch (res.tapIndex) {
                            case 0:
                                this.addToLikes(song);
                                break;
                            case 1:
                                this.addToCollection(song);
                                break;
                            case 2:
                                this.showSongDetail(song);
                                break;
                        }
                    }
                }
            });
        },
        
        // 添加到喜欢
        async addToLikes(song) {
            try {
                // 获取当前页面的全局数据或使用 uni.getStorageSync
                let likedSongs = uni.getStorageSync('likedSongs') || [];
                
                // 检查是否已存在
                const exists = likedSongs.some(s => s.id === song.id);
                if (exists) {
                    uni.showToast({
                        title: '已在喜欢列表中',
                        icon: 'none'
                    });
                    return;
                }
                
                // 添加到喜欢列表
                likedSongs.push(song);
                uni.setStorageSync('likedSongs', likedSongs);
                
                uni.showToast({
                    title: '已添加到喜欢',
                    icon: 'success'
                });
            } catch (error) {
                console.error('添加到喜欢失败:', error);
                uni.showToast({
                    title: '添加失败',
                    icon: 'none'
                });
            }
        },
        
        // 添加到收藏
        async addToCollection(song) {
            try {
                // 获取当前收藏列表
                let collectedSongs = uni.getStorageSync('collectedSongs') || [];
                
                // 检查是否已存在
                const exists = collectedSongs.some(s => s.id === song.id);
                if (exists) {
                    uni.showToast({
                        title: '已在收藏列表中',
                        icon: 'none'
                    });
                    return;
                }
                
                // 添加到收藏列表
                collectedSongs.push(song);
                uni.setStorageSync('collectedSongs', collectedSongs);
                
                uni.showToast({
                    title: '已添加到收藏',
                    icon: 'success'
                });
            } catch (error) {
                console.error('添加到收藏失败:', error);
                uni.showToast({
                    title: '添加失败',
                    icon: 'none'
                });
            }
        },
        
        // 显示歌曲详情
        showSongDetail(song) {
            uni.showModal({
                title: song.title,
                content: `艺术家: ${song.artist}\n时长: ${song.duration || '未知'}`,
                showCancel: false
            });
        },
        
        // 删除自定义歌曲
        deleteCustomSong(song) {
            uni.showModal({
                title: '确认删除',
                content: `确定要删除歌曲"${song.title}"吗？`,
                success: (res) => {
                    if (res.confirm) {
                        // 从歌曲列表中移除
                        this.songList = this.songList.filter(s => s.id !== song.id);
                        
                        // 从本地存储中移除
                        let customSongs = uni.getStorageSync('customSongs') || [];
                        customSongs = customSongs.filter(s => s.id !== song.id);
                        uni.setStorageSync('customSongs', customSongs);
                        
                        // 如果正在播放这首歌，停止播放
                        if (this.currentSong && this.currentSong.id === song.id) {
                            if (this.songList.length > 0) {
                                this.currentSong = this.songList[0];
                            } else {
                                this.currentSong = null;
                            }
                        }
                        
                        uni.showToast({
                            title: '删除成功',
                            icon: 'success'
                        });
                    }
                }
            });
        },
        
        // 显示添加歌曲对话框
        showAddSongDialog() {
            this.showAddDialog = true;
        },
        
        // 关闭添加歌曲对话框
        closeAddDialog() {
            this.showAddDialog = false;
            // 重置表单
            this.newSong = {
                title: '',
                artist: '',
                audioFile: null,
                audioFileName: ''
            };
        },
        
        // 确认添加歌曲
        async confirmAddSong() {
            if (!this.newSong.title) {
                uni.showToast({
                    title: '请输入歌名',
                    icon: 'none'
                });
                return;
            }
            if (!this.newSong.artist) {
                uni.showToast({
                    title: '请输入原唱',
                    icon: 'none'
                });
                return;
            }
            if (!this.newSong.audioFile) {
                uni.showToast({
                    title: '请选择音频文件',
                    icon: 'none'
                });
                return;
            }
            
            // 直接添加本地音频，不需要上传
            try {
                this.addLocalAudio();
                this.closeAddDialog();
            } catch (error) {
                console.error('添加歌曲失败:', error);
                uni.showToast({
                    title: '添加失败',
                    icon: 'none'
                });
            }
        },
        
        // 测试服务器连接
        async testServerConnection() {
            const apiUrl = await this.resolveApiUrl();
            console.log('测试服务器连接:', apiUrl);
            
            try {
                // 直接测试根路径，不用health路径
                const response = await uni.request({
                    url: apiUrl + '/',
                    method: 'GET',
                    timeout: 5000
                });
                
                console.log('服务器连接测试结果:', response);
                
                if (response.statusCode !== 200) {
                    // 如果根路径也失败，直接跳过测试，尝试上传
                    console.log('服务器测试失败，但继续尝试上传');
                    return true;
                }
                
                return true;
            } catch (error) {
                console.error('服务器连接测试失败，跳过测试直接上传:', error);
                // 不抛出错误，直接返回true继续上传
                return true;
            }
        },
        
        // 选择音频文件
        chooseAudioFile() {
            // 显示选择选项
            uni.showActionSheet({
                itemList: ['使用项目中的静态音频文件', '从聊天记录选择音频文件'],
                success: (res) => {
                    if (res.tapIndex === 0) {
                        // 使用静态文件
                        this.useStaticAudio();
                    } else if (res.tapIndex === 1) {
                        // 从聊天记录选择
                        this.chooseFromChat();
                    }
                }
            });
        },
        
        // 使用静态音频文件
        useStaticAudio() {
            // 显示可用的静态音频文件列表
            uni.showActionSheet({
                itemList: this.staticAudioFiles.map(file => file.name),
                success: (res) => {
                    const selectedFile = this.staticAudioFiles[res.tapIndex];
                    if (selectedFile) {
                        this.newSong.audioFile = { path: selectedFile.path };
                        this.newSong.audioFileName = selectedFile.name;
                        console.log('使用静态音频文件:', this.newSong.audioFileName);
                        uni.showToast({
                            title: '已选择静态音频文件',
                            icon: 'success'
                        });
                    }
                }
            });
        },
        
        // 从聊天记录选择音频文件
        chooseFromChat() {
            // #ifdef MP-WEIXIN
            // 微信小程序使用 chooseMessageFile
            uni.chooseMessageFile({
                count: 1,
                type: 'file',
                extension: ['mp3', 'wav', 'm4a', 'flac', 'aac'],
                success: (res) => {
                    console.log('微信小程序文件选择结果:', res);
                    if (res.tempFiles && res.tempFiles.length > 0) {
                        const file = res.tempFiles[0];
                        this.newSong.audioFile = file;
                        this.newSong.audioFileName = file.name;
                        console.log('选择的文件信息:', {
                            name: file.name,
                            size: file.size,
                            path: file.path
                        });
                        uni.showToast({
                            title: '文件选择成功',
                            icon: 'success'
                        });
                    }
                },
                fail: (err) => {
                    console.error('选择文件失败:', err);
                    uni.showToast({
                        title: '请从聊天记录中选择音频文件',
                        icon: 'none',
                        duration: 3000
                    });
                }
            });
            // #endif
            
            // #ifdef H5
            // H5 使用 input file
            const input = document.createElement('input');
            input.type = 'file';
            input.accept = 'audio/*,.mp3,.wav,.m4a,.aac,.flac';
            input.onchange = (e) => {
                const file = e.target.files[0];
                if (file) {
                    console.log('H5选择的文件信息:', {
                        name: file.name,
                        size: file.size,
                        type: file.type
                    });
                    
                    // 验证文件类型
                    const allowedTypes = ['audio/mpeg', 'audio/mp3', 'audio/wav', 'audio/m4a', 'audio/aac', 'audio/flac'];
                    const allowedExtensions = ['.mp3', '.wav', '.m4a', '.aac', '.flac'];
                    const fileExtension = file.name.toLowerCase().substr(file.name.lastIndexOf('.'));
                    
                    if (!file.type.startsWith('audio/') && !allowedExtensions.includes(fileExtension)) {
                        uni.showToast({
                            title: '请选择音频文件（MP3、WAV、M4A等）',
                            icon: 'none',
                            duration: 3000
                        });
                        return;
                    }
                    
                    // 检查文件大小（限制50MB）
                    if (file.size > 50 * 1024 * 1024) {
                        uni.showToast({
                            title: '文件过大，请选择小于50MB的文件',
                            icon: 'none',
                            duration: 3000
                        });
                        return;
                    }
                    
                    // 保存原始文件对象用于上传
                    this.newSong.audioFile = file;
                    this.newSong.audioFileName = file.name;
                    uni.showToast({
                        title: '文件选择成功',
                        icon: 'success'
                    });
                }
            };
            input.click();
            // #endif
            
            // #ifdef APP-PLUS
            // App 使用文件选择
            uni.chooseFile({
                count: 1,
                type: 'file',
                extension: ['.mp3', '.wav', '.m4a', '.aac', '.flac'],
                success: (res) => {
                    console.log('App文件选择结果:', res);
                    if (res.tempFiles && res.tempFiles.length > 0) {
                        const file = res.tempFiles[0];
                        this.newSong.audioFile = file;
                        this.newSong.audioFileName = file.name;
                        uni.showToast({
                            title: '文件选择成功',
                            icon: 'success'
                        });
                    }
                },
                fail: (err) => {
                    console.error('选择文件失败:', err);
                    uni.showToast({
                        title: '文件选择失败',
                        icon: 'none'
                    });
                }
            });
            // #endif
        },
        
        // 上传音频文件（带失败处理）
        async uploadAudioFile(retryCount = 0) {
            const apiUrl = config.apiUrl;
            const maxRetries = 3;
            
            return new Promise((resolve, reject) => {
                // #ifdef MP-WEIXIN
                // 微信小程序上传
                console.log('开始上传到:', apiUrl + '/api/upload/audio', '重试次数:', retryCount);
                
                // 显示上传进度
                uni.showLoading({
                    title: retryCount > 0 ? `重试上传中(${retryCount}/${maxRetries})...` : '正在上传...',
                    mask: true
                });
                
                const uploadTask = uni.uploadFile({
                    url: apiUrl + '/api/upload/audio',
                    filePath: this.newSong.audioFile.path,
                    name: 'audio',
                    timeout: 60000, // 60秒超时
                    formData: {
                        title: this.newSong.title,
                        artist: this.newSong.artist
                    },
                    success: (res) => {
                        uni.hideLoading();
                        console.log('上传成功:', res);
                        
                        // 检查HTTP状态码
                        if (res.statusCode !== 200) {
                            const error = new Error(`服务器错误: ${res.statusCode}`);
                            this.handleUploadError(error, retryCount, maxRetries, resolve, reject);
                            return;
                        }
                        
                        try {
                            const data = JSON.parse(res.data);
                            console.log('微信小程序解析后的数据:', data);
                            if (data.code === 0) {
                                // 上传成功 - 修复字段名不匹配问题
                                const audioUrl = data.data.audioUrl || data.data.url;
                                console.log('准备添加歌曲，音频URL:', audioUrl);
                                this.addNewSongWithUrl(audioUrl);
                                resolve();
                            } else {
                                const error = new Error(data.message || '服务器返回错误');
                                this.handleUploadError(error, retryCount, maxRetries, resolve, reject);
                            }
                        } catch (e) {
                            const error = new Error('解析服务器响应失败');
                            this.handleUploadError(error, retryCount, maxRetries, resolve, reject);
                        }
                    },
                    fail: (err) => {
                        uni.hideLoading();
                        console.error('上传失败:', err);
                        
                        // 根据错误类型提供具体的错误信息
                        let error;
                        if (err.errMsg) {
                            if (err.errMsg.includes('timeout')) {
                                error = new Error('上传超时，请检查网络连接');
                            } else if (err.errMsg.includes('fail')) {
                                error = new Error('网络连接失败，请检查网络设置');
                            } else if (err.errMsg.includes('abort')) {
                                error = new Error('上传被中断');
                            } else {
                                error = new Error(`上传失败: ${err.errMsg}`);
                            }
                        } else {
                            error = new Error('未知上传错误');
                        }
                        
                        this.handleUploadError(error, retryCount, maxRetries, resolve, reject);
                    }
                });
                
                // 监听上传进度
                uploadTask.onProgressUpdate((res) => {
                    console.log('上传进度:', res.progress + '%');
                    const title = retryCount > 0 
                        ? `重试上传中 ${res.progress}% (${retryCount}/${maxRetries})`
                        : `上传中 ${res.progress}%`;
                    uni.showLoading({
                        title: title,
                        mask: true
                    });
                });
                // #endif
                
                // #ifdef H5
                // H5 使用 FormData 上传
                const formData = new FormData();
                formData.append('audio', this.newSong.audioFile);
                formData.append('title', this.newSong.title);
                formData.append('artist', this.newSong.artist);
                
                console.log('H5上传详细信息:', {
                    url: apiUrl + '/api/upload/audio',
                    retryCount: retryCount,
                    fileInfo: {
                        name: this.newSong.audioFile.name,
                        size: this.newSong.audioFile.size,
                        type: this.newSong.audioFile.type
                    },
                    title: this.newSong.title,
                    artist: this.newSong.artist
                });
                
                // 显示上传提示
                uni.showLoading({
                    title: retryCount > 0 ? `重试上传中(${retryCount}/${maxRetries})...` : '正在上传...',
                    mask: true
                });
                
                // 创建 AbortController 用于取消请求
                const controller = new AbortController();
                const timeoutId = setTimeout(() => {
                    controller.abort();
                }, 60000); // 60秒超时
                
                fetch(apiUrl + '/api/upload/audio', {
                    method: 'POST',
                    body: formData,
                    signal: controller.signal,
                    mode: 'cors', // 明确设置CORS模式
                    credentials: 'omit' // 不发送凭证
                })
                .then(response => {
                    clearTimeout(timeoutId);
                    console.log('H5上传响应:', {
                        status: response.status,
                        statusText: response.statusText,
                        ok: response.ok
                    });
                    
                    if (!response.ok) {
                        let errorMsg;
                        switch (response.status) {
                            case 413:
                                errorMsg = '文件过大，请选择较小的音频文件';
                                break;
                            case 415:
                                errorMsg = '不支持的文件格式，请选择MP3、WAV等音频格式';
                                break;
                            case 500:
                                errorMsg = '服务器内部错误，请稍后重试';
                                break;
                            case 503:
                                errorMsg = '服务器暂不可用，请稍后重试';
                                break;
                            case 404:
                                errorMsg = '上传接口不存在，请检查服务器配置';
                                break;
                            default:
                                errorMsg = `网络错误 (${response.status}: ${response.statusText})`;
                        }
                        throw new Error(errorMsg);
                    }
                    return response.json();
                })
                .then(data => {
                    uni.hideLoading();
                    console.log('H5上传成功，服务器响应:', data);
                    if (data.code === 0) {
                        // 上传成功 - 修复字段名不匹配问题
                        const audioUrl = data.data.audioUrl || data.data.url;
                        console.log('准备添加歌曲，音频URL:', audioUrl);
                        this.addNewSongWithUrl(audioUrl);
                        resolve();
                    } else {
                        const error = new Error(data.message || '服务器返回错误');
                        this.handleUploadError(error, retryCount, maxRetries, resolve, reject);
                    }
                })
                .catch(err => {
                    clearTimeout(timeoutId);
                    uni.hideLoading();
                    console.error('H5上传失败详细信息:', err);
                    
                    // 根据错误类型提供具体的错误信息
                    let error;
                    if (err.name === 'AbortError') {
                        error = new Error('上传超时，请检查网络连接');
                    } else if (err.message.includes('Failed to fetch') || err.message.includes('fetch')) {
                        error = new Error('网络连接失败，请检查服务器是否启动');
                    } else if (err.message.includes('NetworkError')) {
                        error = new Error('网络错误，请检查网络连接');
                    } else if (err.message.includes('CORS')) {
                        error = new Error('跨域请求失败，请检查服务器CORS配置');
                    } else {
                        error = err;
                    }
                    
                    this.handleUploadError(error, retryCount, maxRetries, resolve, reject);
                });
                // #endif
            });
        },
        
        // 处理上传错误和重试逻辑
        handleUploadError(error, retryCount, maxRetries, resolve, reject) {
            console.error('上传错误处理:', error.message, '重试次数:', retryCount);
            
            // 如果还有重试机会且不是用户主动取消的错误
            if (retryCount < maxRetries && 
                !error.message.includes('用户取消') && 
                !error.message.includes('文件过大') &&
                !error.message.includes('不支持的文件格式')) {
                
                // 显示重试提示
                uni.showModal({
                    title: '上传失败',
                    content: `${error.message}\n\n是否重试？(${retryCount + 1}/${maxRetries})`,
                    confirmText: '重试',
                    cancelText: '取消',
                    success: (res) => {
                        if (res.confirm) {
                            // 延迟重试，避免立即重试
                            setTimeout(() => {
                                this.uploadAudioFile(retryCount + 1)
                                    .then(resolve)
                                    .catch(reject);
                            }, 1000 * (retryCount + 1)); // 递增延迟
                        } else {
                            reject(new Error('用户取消上传'));
                        }
                    }
                });
            } else {
                // 达到最大重试次数或不可重试的错误，显示详细错误信息
                this.showUploadErrorDialog(error, retryCount >= maxRetries);
                reject(error);
            }
        },
        
        // 显示上传错误对话框
        showUploadErrorDialog(error, isMaxRetry) {
            let title = '上传失败';
            let content = error.message;
            
            // 根据错误类型提供解决建议
            if (error.message.includes('网络')) {
                content += '\n\n建议：\n• 检查网络连接\n• 尝试切换网络环境\n• 稍后重试';
            } else if (error.message.includes('超时')) {
                content += '\n\n建议：\n• 检查网络速度\n• 选择较小的音频文件\n• 稍后重试';
            } else if (error.message.includes('文件过大')) {
                content += '\n\n建议：\n• 压缩音频文件\n• 选择较短的音频\n• 使用MP3格式';
            } else if (error.message.includes('格式')) {
                content += '\n\n建议：\n• 使用MP3、WAV、M4A格式\n• 确保文件未损坏';
            } else if (error.message.includes('服务器')) {
                content += '\n\n建议：\n• 稍后重试\n• 联系技术支持';
            }
            
            if (isMaxRetry) {
                title = '上传多次失败';
                content = `经过多次重试仍然失败：\n${content}`;
            }
            
            uni.showModal({
                title: title,
                content: content,
                showCancel: false,
                confirmText: '确定'
            });
        },
        
        // 保存歌曲信息到数据库
        async saveSongToDatabase(songName, artistName) {
            try {
                const apiUrl = await this.resolveApiUrl();
                // 仅保存歌名与原唱；先查避免 409（兼容 name/title 等字段）
                const songExist = await this.existsOnServer(apiUrl, '/api/songs', ['name','title'], songName);
                if (!songExist) {
                    // 修复：使用正确的字段名 title 而不是 name
                    await this.requestJson(apiUrl, '/api/songs', { 
                        title: songName, 
                        artist: artistName,
                        song_url: '', // 添加默认值
                        cover_url: '' // 添加默认值
                    });
                }
                const singerExist = await this.existsOnServer(apiUrl, '/api/songers', ['name','artist','singer','singer_name'], artistName);
                if (!singerExist) {
                    await this.requestJson(apiUrl, '/api/songers', { name: artistName });
                }
                return true;
            } catch (e) {
                // 离线缓存队列（去重后再入队），不抛错
                let pending = uni.getStorageSync('pendingSongSaves') || [];
                const dup = pending.some(p => p.name === songName && p.artist === artistName);
                if (!dup) {
                    pending.unshift({
                        name: songName,
                        artist: artistName,
                        time: Date.now()
                    });
                    uni.setStorageSync('pendingSongSaves', pending);
                }
                return true;
            }
        },
        
        // 添加本地音频文件
        async addLocalAudio() {
            // 生成本地音频URL
            let audioUrl = '';
            
            // 检查是否是静态文件路径
            // 查找匹配的静态文件
            const matchedFile = this.staticAudioFiles.find(file => 
                this.newSong.audioFileName && this.newSong.audioFileName.includes(file.name)
            );
            
            if (matchedFile) {
                // 使用静态文件路径
                audioUrl = matchedFile.path;
                console.log('使用静态文件路径:', audioUrl);
            } else if (this.newSong.audioFile && this.newSong.audioFile.path && this.newSong.audioFile.path.includes('static')) {
                // 如果文件路径包含static，直接使用
                audioUrl = this.newSong.audioFile.path;
                console.log('使用文件路径:', audioUrl);
            } else {
                // #ifdef MP-WEIXIN
                // 微信小程序：使用临时文件路径
                audioUrl = this.newSong.audioFile.path;
                // #endif
                
                // #ifdef H5
                // H5：创建本地URL
                audioUrl = URL.createObjectURL(this.newSong.audioFile);
                // #endif
            }
            
            const newSong = {
                id: Date.now(),
                title: this.newSong.title,
                artist: this.newSong.artist,
                cover_url: 'https://ai-public.mastergo.com/ai/img_res/647cde825adf712e96b3bc66cb67656c.jpg',
                audio_url: audioUrl,
                duration: '00:00',
                isCustom: true,
                isLocal: true
            };
            
            console.log('添加本地音频:', newSong);
            
            // 先本地立即添加，提升体验
            this.songList.unshift(newSong);
            let customSongs = uni.getStorageSync('customSongs') || [];
            customSongs.unshift(newSong);
            uni.setStorageSync('customSongs', customSongs);

            // 后台异步保存数据库（失败走离线队列，不打断不弹错）
            this.saveSongToDatabase(this.newSong.title, this.newSong.artist)
                .then(() => {
                    console.log('歌曲信息已保存到数据库');
                })
                .catch((error) => {
                    console.warn('后台保存到数据库失败:', error);
                });
            
            // 显示成功提示，并询问是否立即播放
            uni.showModal({
                title: '添加成功',
                content: `歌曲"${newSong.title}"已添加到列表，是否立即播放？`,
                confirmText: '播放',
                cancelText: '稍后',
                success: (res) => {
                    if (res.confirm) {
                        this.playSong(newSong);
                    }
                }
            });
            
            // 重置表单
            this.newSong = {
                title: '',
                artist: '',
                audioFile: null,
                audioFileName: ''
            };
        },
        
        // 使用服务器返回的 URL 添加歌曲
        addNewSongWithUrl(audioUrl) {
            // 确保 audioUrl 是完整的 URL
            let fullAudioUrl = audioUrl;
            if (audioUrl.startsWith('/uploads/')) {
                // 如果是相对路径，拼接完整的服务器地址
                const apiUrl = config.apiUrl;
                fullAudioUrl = apiUrl + audioUrl;
            }
            
            const newSong = {
                id: Date.now(),
                title: this.newSong.title,
                artist: this.newSong.artist,
                cover_url: 'https://ai-public.mastergo.com/ai/img_res/647cde825adf712e96b3bc66cb67656c.jpg',
                audio_url: fullAudioUrl,
                duration: '00:00',
                isCustom: true
            };
            
            console.log('添加新歌曲:', newSong);
            console.log('音频URL:', fullAudioUrl);
            
            // 添加到歌曲列表开头
            this.songList.unshift(newSong);
            
            // 保存到本地存储
            let customSongs = uni.getStorageSync('customSongs') || [];
            customSongs.unshift(newSong);
            uni.setStorageSync('customSongs', customSongs);
            
            // 显示成功提示，并询问是否立即播放
            uni.showModal({
                title: '添加成功',
                content: `歌曲"${newSong.title}"已添加到列表，是否立即播放？`,
                confirmText: '播放',
                cancelText: '稍后',
                success: (res) => {
                    if (res.confirm) {
                        this.playSong(newSong);
                    }
                }
            });
            
            // 重置表单
            this.newSong = {
                title: '',
                artist: '',
                audioFile: null,
                audioFileName: ''
            };
        },
        
        // 验证音频URL是否可访问
        async validateAudioUrl(audioUrl) {
            try {
                console.log('验证音频URL:', audioUrl);
                
                // #ifdef H5
                // H5环境可以直接测试URL
                const response = await fetch(audioUrl, { method: 'HEAD' });
                return response.ok;
                // #endif
                
                // #ifdef MP-WEIXIN
                // 微信小程序环境，简单返回true，实际播放时会验证
                return true;
                // #endif
                
                return true;
            } catch (error) {
                console.error('音频URL验证失败:', error);
                return false;
            }
        },
        

    }
}
</script>

<style>
/* 容器 */
.container {
    background: linear-gradient(180deg, #f0f4ff 0%, #fef5ff 50%, #fff0f6 100%);
    min-height: 100vh;
    position: relative;
}

/* 顶部导航栏 */
.header {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    height: 120rpx;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    z-index: 50;
    padding: 0 40rpx;
    display: flex; 
    justify-content: space-between;
    align-items: center;
    box-shadow: 0 8rpx 32rpx rgba(102, 126, 234, 0.25);
    backdrop-filter: blur(20rpx);
}

.logo {
    display: flex;
    align-items: center;
    gap: 12rpx;
}

.logo-icon {
    font-size: 48rpx;
    animation: pulse 2s ease-in-out infinite;
}

@keyframes pulse {
    0%, 100% { transform: scale(1); }
    50% { transform: scale(1.1); }
}

.logo-text {
    font-size: 36rpx;
    font-weight: bold;
    color: #ffffff;
    letter-spacing: 2rpx;
    text-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.2);
}

.header-actions {
    display: flex;
    gap: 20rpx;
}

.header-btn {
    width: 70rpx;
    height: 70rpx;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.2);
    display: flex;
    align-items: center;
    justify-content: center;
    backdrop-filter: blur(10rpx);
    transition: all 0.3s ease;
}

.header-btn:active {
    transform: scale(0.9);
    background: rgba(255, 255, 255, 0.3);
}

.header-icon {
    font-size: 36rpx;
}


/* 内容区域 */
.content {
    margin-top: 120rpx;
    margin-bottom: 140rpx;
    padding: 0 30rpx;
    min-height: 100vh;
}

/* 标签栏 */
.tabs {
    display: flex;
    padding: 20rpx 0;
}

.tab {
    flex: 1;
    text-align: center;
    padding: 15rpx 0;
    font-size: 28rpx;
    color: #888888;
}

.tab.active {
    color: #7C4DFF;
    border-bottom: 4rpx solid #7C4DFF;
}

/* 横幅 */
.banner {
    margin: 30rpx 0 40rpx 0;
    border-radius: 28rpx;
    overflow: hidden;
    box-shadow: 0 12rpx 40rpx rgba(102, 126, 234, 0.25);
    position: relative;
}

.banner-swiper {
    height: 360rpx;
}

.banner-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(180deg, transparent 0%, rgba(0, 0, 0, 0.3) 100%);
    z-index: 1;
}

.banner-image {
    width: 100%;
    height: 360rpx;
    object-fit: cover;
}

/* 区块通用样式 */
.section {
    margin-bottom: 50rpx;
    position: relative;
}

.section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24rpx;
}

.section-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #2c3e50;
    display: flex;
    align-items: center;
    gap: 8rpx;
}

.section-more {
    font-size: 26rpx;
    color: #667eea;
    font-weight: 500;
}

.song-count {
    font-size: 24rpx;
    color: #95a5a6;
    background: rgba(102, 126, 234, 0.1);
    padding: 8rpx 16rpx;
    border-radius: 20rpx;
}

/* 添加歌曲按钮 */
.add-song-btn {
    position: absolute;
    top: 0;
    right: 0;
    width: 70rpx;
    height: 70rpx;
    border: none;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 40rpx;
    color: #ffffff;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    box-shadow: 0 6rpx 20rpx rgba(102, 126, 234, 0.4);
    transition: all 0.3s ease;
    z-index: 10;
}

.add-song-btn:active {
    transform: scale(0.9) rotate(90deg);
    box-shadow: 0 4rpx 16rpx rgba(102, 126, 234, 0.5);
}

.add-icon {
    font-size: 44rpx;
    color: #ffffff;
    font-weight: 300;
    line-height: 1;
}

/* 推荐歌单 */
.playlist-scroll {
    width: 100%;
    white-space: nowrap; /* 禁止换行 */
}

.playlist-grid {
    display: inline-flex; /* 改为inline-flex以在scroll-view中横向排列 */
    gap: 20rpx; /* 添加卡片之间的间距 */
}

.playlist-card {
    width: 260rpx;
    display: inline-block;
    vertical-align: top;
    background: #ffffff;
    border-radius: 24rpx;
    padding: 16rpx;
    box-shadow: 0 6rpx 24rpx rgba(102, 126, 234, 0.12);
    transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
    position: relative;
    overflow: hidden;
    border: 1rpx solid rgba(102, 126, 234, 0.08);
}

.playlist-card::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(135deg, rgba(102, 126, 234, 0.08) 0%, rgba(118, 75, 162, 0.08) 100%);
    opacity: 0;
    transition: opacity 0.3s ease;
}

.playlist-card:active {
    transform: translateY(-8rpx) scale(1.02);
    box-shadow: 0 12rpx 40rpx rgba(102, 126, 234, 0.25);
}

.playlist-card:active::before {
    opacity: 1;
}

/* 创建歌单卡片 */
.create-playlist-card {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    background: linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%);
    border: 2rpx dashed transparent;
    background-clip: padding-box;
    position: relative;
    min-height: 290rpx;
}

.create-playlist-card::after {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    border-radius: 20rpx;
    padding: 2rpx;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    -webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
    -webkit-mask-composite: xor;
    mask-composite: exclude;
    pointer-events: none;
}

.create-icon {
    width: 100rpx;
    height: 100rpx;
    border-radius: 50%;
    background: linear-gradient(135deg, rgba(102, 126, 234, 0.2) 0%, rgba(118, 75, 162, 0.2) 100%);
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 60rpx;
    background-clip: text;
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-image: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    margin-bottom: 20rpx;
}

.create-playlist-card:active {
    background: linear-gradient(135deg, rgba(102, 126, 234, 0.2) 0%, rgba(118, 75, 162, 0.2) 100%);
}

.playlist-image {
    width: 100%;
    height: 260rpx;
    border-radius: 20rpx;
    margin-bottom: 16rpx;
    object-fit: cover;
    position: relative;
    z-index: 1;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
}

.playlist-title {
    font-size: 28rpx;
    font-weight: bold;
    display: block;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    color: #2c3e50;
    margin-bottom: 8rpx;
    position: relative;
    z-index: 1;
}

.playlist-info {
    font-size: 22rpx;
    color: #95a5a6;
    display: block;
    position: relative;
    z-index: 1;
}

/* 最近播放 */
.song-list {
    display: flex;
    flex-direction: column;
}

.song-item {
    display: flex;
    align-items: center;
    padding: 20rpx 24rpx;
    background: #ffffff;
    border-radius: 20rpx;
    margin-bottom: 16rpx;
    box-shadow: 0 4rpx 16rpx rgba(102, 126, 234, 0.08);
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    position: relative;
    overflow: hidden;
    border: 1rpx solid rgba(102, 126, 234, 0.05);
}

.song-item::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(135deg, rgba(102, 126, 234, 0.05) 0%, rgba(118, 75, 162, 0.05) 100%);
    opacity: 0;
    transition: opacity 0.3s ease;
}

.song-item:active {
    transform: scale(0.98);
    box-shadow: 0 6rpx 24rpx rgba(102, 126, 234, 0.2);
}

.song-item:active::before {
    opacity: 1;
}

.song-index {
    width: 50rpx;
    height: 50rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24rpx;
    font-weight: bold;
    color: #95a5a6;
    margin-right: 16rpx;
    position: relative;
    z-index: 1;
}

.song-image {
    width: 100rpx;
    height: 100rpx;
    border-radius: 16rpx;
    margin-right: 20rpx;
    object-fit: cover;
    position: relative;
    z-index: 1;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.song-info {
    flex: 1;
    position: relative;
    z-index: 1;
    min-width: 0;
}

.song-title {
    font-size: 30rpx;
    font-weight: bold;
    display: block;
    color: #2c3e50;
    margin-bottom: 8rpx;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.song-artist {
    font-size: 24rpx;
    color: #95a5a6;
    display: flex;
    align-items: center;
    gap: 4rpx;
}

.song-actions {
    display: flex;
    align-items: center;
    gap: 12rpx;
    position: relative;
    z-index: 1;
}

.play-indicator {
    animation: bounce 1s ease-in-out infinite;
}

@keyframes bounce {
    0%, 100% { transform: translateY(0); }
    50% { transform: translateY(-4rpx); }
}

.playing-icon {
    font-size: 32rpx;
}

.song-more {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 50%;
    transition: all 0.3s ease;
}

.song-more:active {
    background: rgba(102, 126, 234, 0.1);
    transform: scale(0.9);
}

/* 底部播放栏 */
.player-bar {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    height: 120rpx;
    background-color: #ffffff;
    border-top: 1rpx solid #eeeeee;
    padding: 0 30rpx;
    display: flex;
    align-items: center;
}

.player-image {
    width: 80rpx;
    height: 80rpx;
    border-radius: 16rpx;
    margin-right: 20rpx;
}

.player-info {
    flex: 1;
}

.player-title {
    font-size: 28rpx;
    font-weight: 500;
    display: block;
}

.player-artist {
    font-size: 24rpx;
    color: #888888;
    display: block;
}

.player-controls {
    display: flex;
    align-items: center;
}

.icon {
    font-size: 40rpx;
    color: #888888;
    margin-left: 30rpx;
}

.play-icon {
    color: #7C4DFF;
}

/* 加载状态 */
.loading {
    text-align: center;
    padding: 40rpx 0;
    color: #888888;
    font-size: 28rpx;
}


/* 添加歌曲弹窗样式 */
.dialog-mask {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(135deg, rgba(102, 126, 234, 0.3) 0%, rgba(118, 75, 162, 0.3) 100%);
    backdrop-filter: blur(10rpx);
    z-index: 1000;
    display: flex;
    justify-content: center;
    align-items: center;
}

.dialog-content {
    width: 600rpx;
    background: linear-gradient(135deg, #ffffff 0%, #f8f9fe 100%);
    border-radius: 24rpx;
    overflow: hidden;
    box-shadow: 0 20rpx 60rpx rgba(102, 126, 234, 0.3);
}

.dialog-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx;
    background: linear-gradient(135deg, rgba(102, 126, 234, 0.05) 0%, rgba(118, 75, 162, 0.05) 100%);
    border-bottom: 1rpx solid rgba(102, 126, 234, 0.1);
}

.dialog-title {
    font-size: 32rpx;
    font-weight: 500;
    color: #333333;
}

.dialog-close {
    font-size: 50rpx;
    color: #888888;
    line-height: 1;
    cursor: pointer;
}

.dialog-body {
    padding: 30rpx;
}

.form-item {
    margin-bottom: 30rpx;
}

.form-item:last-child {
    margin-bottom: 0;
}

.form-label {
    display: block;
    font-size: 28rpx;
    color: #333333;
    margin-bottom: 15rpx;
}

.form-input {
    width: 100%;
    height: 80rpx;
    padding: 0 20rpx;
    border: 1rpx solid #dddddd;
    border-radius: 10rpx;
    font-size: 28rpx;
    box-sizing: border-box;
}

.file-select {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 80rpx;
    padding: 0 20rpx;
    border: 1rpx solid #dddddd;
    border-radius: 10rpx;
    background-color: #f9f9f9;
}

.file-text {
    flex: 1;
    font-size: 28rpx;
    color: #666666;
}

.file-icon {
    font-size: 40rpx;
}

.dialog-footer {
    display: flex;
    border-top: 1rpx solid #eeeeee;
}

.dialog-btn {
    flex: 1;
    height: 90rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 30rpx;
}

.dialog-btn-cancel {
    color: #888888;
    border-right: 1rpx solid #eeeeee;
}

.dialog-btn-confirm {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    font-weight: bold;
}

.dialog-btn:active {
    background-color: #f5f5f5;
}

</style>